package com.exam.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.entity.ExamManage;
import com.exam.entity.FillQuestion;
import com.exam.entity.JudgeQuestion;
import com.exam.entity.MultiQuestion;
import com.exam.mapper.ExamManageMapper;
import com.exam.service.ExamManageService;
import com.exam.util.MapListToEntityList;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class ExamManageServiceImpl implements ExamManageService {
    @Resource
    private ExamManageMapper examManageMapper;


    @Override
    public List<ExamManage> findAll() {
        return examManageMapper.findAll();
    }

    @Override
    public IPage<ExamManage> findAll(Page<ExamManage> page) {
        return examManageMapper.findAll(page);
    }

    @Override
    public ExamManage findById(Integer examCode) {
        return examManageMapper.findById(examCode);
    }

    @Override
    public int delete(Integer examCode) {
        return examManageMapper.delete(examCode);
    }

    @Override
    public int update(ExamManage exammanage) {
        return examManageMapper.update(exammanage);
    }

    @Override
    public int add(ExamManage exammanage) {
        return examManageMapper.add(exammanage);
    }

    @Override
    public ExamManage findOnlyPaperId() {
        return examManageMapper.findOnlyPaperId();
    }

    @Override
    public ResponseEntity<ByteArrayResource> exportAllFile() throws Exception {

        this.exportOneFile();
        // 创建一个临时目录来存放生成的文件
        Path tempDirectory = Files.createTempDirectory("C:\\Users\\Admin\\Downloads");

        for (int i = 0; i < 100; i++) {

        }

        // 生成多个Word文档
        Path document1 = tempDirectory.resolve("document1.docx");
        Path document2 = tempDirectory.resolve("document2.docx");
        // ... 生成更多文件的代码 ...

        // 创建ZIP文件
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            // 添加文件到ZIP
            Files.walk(tempDirectory)
                .filter(Files::isRegularFile)
                .forEach(path -> {
                    ZipEntry zipEntry = new ZipEntry(tempDirectory.relativize(path).toString());
                    try {
                        zos.putNextEntry(zipEntry);
                        byte[] bytes = Files.readAllBytes(path);
                        zos.write(bytes);
                        zos.closeEntry();
                    } catch (IOException e) {
                        // 处理异常
                    }
                });
        }

        // 设置文件名
        String zipFilename = "documents.zip";

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", zipFilename);

        // 创建ByteArrayResource对象
        ByteArrayResource resource = new ByteArrayResource(baos.toByteArray()) {
            @Override
            public String getFilename() {
                return zipFilename;
            }
        };

        // 返回响应
        return ResponseEntity.ok()
            .headers(headers)
            .contentLength(baos.size())
            .body(resource);
    }

    @Override
    public ResponseEntity<byte[]> exportFile(HashMap<String, HashMap<String,List<Map<String, Object>>>> examVo) throws IOException, Exception {
        List<ExamManage> all = examManageMapper.findAll();

        // 获取examVo的属性
        HashMap<String, List<Map<String, Object>>> map = examVo.get("aa");

        List<MultiQuestion> multiQuestionList = MapListToEntityList.mapListToEntityList(map.get("1"), MultiQuestion.class);
        List<FillQuestion> fillQuestionList = MapListToEntityList.mapListToEntityList(map.get("2"), FillQuestion.class);
        List<JudgeQuestion> judgeQuestionList = MapListToEntityList.mapListToEntityList(map.get("3"), JudgeQuestion.class);

        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();

        // 设置文档标题
        run.setText(multiQuestionList.get(0).getSubject());
        run.setFontSize(24);
        run.setBold(true);
        run.addCarriageReturn();

        run.setText("选择题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        multiQuestionList.forEach(multiQuestion -> {
            run.setText(multiQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("A." + multiQuestion.getAnswerA());
            run.addCarriageReturn();
            run.setText("B." + multiQuestion.getAnswerB());
            run.addCarriageReturn();
            run.setText("C." + multiQuestion.getAnswerC());
            run.addCarriageReturn();
            run.setText("D." + multiQuestion.getAnswerD());
            run.addCarriageReturn();
            run.setText("答案：" + multiQuestion.getRightAnswer());
            run.addCarriageReturn();
        });

        run.setText("填空题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        fillQuestionList.forEach(fillQuestion -> {
            run.setText(fillQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("答案：" + fillQuestion.getAnswer());
        });

        run.setText("判断题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        judgeQuestionList.forEach(judgeQuestion -> {
            run.setText(judgeQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("答案：" + judgeQuestion.getAnswer());
        });

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.write(baos);
            document.close(); // 确保关闭文档
            baos.close(); // 确保关闭流

            byte[] documentContent = baos.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "\"" + "exam.docx" + "\"");
            return ResponseEntity.ok().headers(headers).body(documentContent);
        } catch (Exception e) {
            // 处理异常，可以记录日志或者返回错误信息
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }



    public void exportOneFile() {

        List<FillQuestion> fillQuestionList = examManageMapper.getFillQuestionList();
        List<JudgeQuestion> judgeQuestionList = examManageMapper.getJudgeQuestionList();
        List<MultiQuestion> multiQuestionList = examManageMapper.getMultiQuestionList();

        /*XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();

        // 设置文档标题
        run.setText(multiQuestionList.get(0).getSubject());
        run.setFontSize(24);
        run.setBold(true);
        run.addCarriageReturn();

        run.setText("选择题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        multiQuestionList.forEach(multiQuestion -> {
            run.setText(multiQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("A." + multiQuestion.getAnswerA());
            run.addCarriageReturn();
            run.setText("B." + multiQuestion.getAnswerB());
            run.addCarriageReturn();
            run.setText("C." + multiQuestion.getAnswerC());
            run.addCarriageReturn();
            run.setText("D." + multiQuestion.getAnswerD());
            run.addCarriageReturn();
            run.setText("答案：" + multiQuestion.getRightAnswer());
            run.addCarriageReturn();
        });

        run.setText("填空题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        fillQuestionList.forEach(fillQuestion -> {
            run.setText(fillQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("答案：" + fillQuestion.getAnswer());
        });

        run.setText("判断题");
        run.setFontSize(16);
        run.setBold(true);
        run.addCarriageReturn();
        judgeQuestionList.forEach(judgeQuestion -> {
            run.setText(judgeQuestion.getQuestion());
            run.setFontSize(14);
            run.setBold(false);
            run.addCarriageReturn();
            run.setText("答案：" + judgeQuestion.getAnswer());
        });

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.write(baos);
            document.close(); // 确保关闭文档
            baos.close(); // 确保关闭流

            byte[] documentContent = baos.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "\"" + "exam.docx" + "\"");
            return ResponseEntity.ok().headers(headers).body(documentContent);
        } catch (Exception e) {
            // 处理异常，可以记录日志或者返回错误信息
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }*/
    }

}
